package com.spider.utils;

import com.alibaba.fastjson.JSONObject;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

public class HttpClient {
    public static String get(String requestURL, String charset) {
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[10485760];
                int length;
                while ((length = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                }
                String jsonString = baos.toString();
                is.close();
                baos.close();
                conn.disconnect();
                return jsonString;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject get(String requestURL, String charset, String proxyIp, Integer proxyPort) {
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort)));
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[10485760];
                int length;
                while ((length = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                }
                String jsonString = baos.toString();
                is.close();
                baos.close();
                conn.disconnect();
                return JSONObject.parseObject(jsonString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String requestURL, String charset, Map<String, String> params, String proxyIp, Integer proxyPort) {
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            StringBuilder builder = getParamString(params);
            OutputStream outputStream = conn.getOutputStream();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                String length = null;
                StringBuilder sb = new StringBuilder();
                while ((length = reader.readLine()) != null) {
                    sb.append(length);
                }
                reader.close();
                outputStream.close();
                conn.disconnect();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static StringBuilder getParamString(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> param = iterator.next();
            sb.append(param.getKey()).append("=").append(param.getValue());
            if (iterator.hasNext()) {
                sb.append("&");
            }
        }
        return sb;
    }

    public static void downloadFile(String downloadUrl, String directory, String fileName) {
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
                String desktopPath = desktopDir.getAbsolutePath();
                InputStream is = conn.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                File path = new File(desktopPath + File.separator + directory, fileName);
                int length;
                byte[] buffer = new byte[10485760];
                if (!path.getParentFile().exists()) {
                    path.getParentFile().mkdirs();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(path);
                while ((length = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                }
                fileOutputStream.write(baos.toByteArray());
                is.close();
                baos.close();
                fileOutputStream.close();
                conn.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
